﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

using SIPO.Library.DomainObject.Administration.UserManagement;
using SIPO.Library.DataAccess.Administration.UserManagement;
using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DataAccess.Transaction;
using SIPO.Library.DomainObject.Transaction;
using SIPO.Web.Support;

using System.Configuration;
using System.Text;

namespace SIPO.Web
{
    public partial class SIPOMaster : BaseMasterPage
    {

        private recMenuRepo menuDal = null;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                Page.Header.DataBind();
                LinkLogout.HRef = Support.Helper.GetAppVirtualPath(this.Page) + "/forms/authentication/logout.aspx";
                ltrUserName.Text = base.UserLoggedIn;

                menuDal = new recMenuRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);

                LoadMenu(base.UserID);
                LoadSiteMap(base.MenuID);
            }

        }

        private void LoadMenu(int UserID)
        {
            if (base.DebtorID.HasValue)
            {
                recDebtorRepo debtorDal = new recDebtorRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                var debtor = debtorDal.GetById(base.DebtorID.Value);
                if (debtor != null)
                    ltrSatKer.Text = "Perusahaan : " + debtor.DebtorName;
            }
            else if (base.RegistrationID > 0)
            {
                recRegistrationRepo registrationDal = new recRegistrationRepo(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
                var registration = registrationDal.GetById(base.RegistrationID);
                if (registration != null)
                    ltrSatKer.Text = "Perusahaan : " + registration.PreDebtorName;
            }
            else
            {
                ltrSatKer.Text = "Otoritas Jasa Keuangan";
            }

            List<int> roleIds = new List<int>();

            Membership membership = new Membership(ConfigurationManager.ConnectionStrings["SIPOConn"].ConnectionString);
            membership.GetRoles(UserID).ForEach(delegate(recUserRole role)
            {
                roleIds.Add(role.RoleID.Value);
            });

            List<recMenu> menus = membership.GetMenusByRoleIDs(roleIds);

            mnMaster.Items.Clear(); // Clear Menu Items
            AddItems(mnMaster.Items, null, menus); // set Null for the first time to load BaseParent.

        }

        private void LoadSiteMap(int menuId)
        {
            var currentMenu = menuDal.GetHierarchyList("WHERE MenuID = " + menuId);

            StringBuilder sbSitemap = new StringBuilder();

            sbSitemap.AppendFormat("<li><a href=\"{0}\" title=\"Home\">", Support.Helper.GetAppVirtualPath(this.Page) + "/default.aspx");
            sbSitemap.AppendFormat("<img src=\"{0}\" alt=\"Home\" class=\"home\" />", ResolveUrl("images/breadcrumb/home.gif"));
            sbSitemap.Append("</a></li>");

            Stack<recMenu> siteMenus = new Stack<recMenu>();

            if (currentMenu.Count > 0)
            {
                var count = Convert.ToInt32(currentMenu[0].Level) + 1;

                var currentId = currentMenu[0].MenuID;

                for (var i = 0; i < count; i++)
                {
                    recMenu dto = menuDal.GetById(currentId);
                    if (dto.MenuID > 0)
                    {
                        siteMenus.Push(dto);
                        currentId = (dto.ParentMenuID.HasValue) ? dto.ParentMenuID.Value : 0;
                    }
                }

                foreach (recMenu dto in siteMenus)
                {
                    var navigateUrl = (string.IsNullOrEmpty(dto.URL) ? "#" : dto.URL + (dto.URL.Contains('?') ? "&menuid=" + dto.MenuID : "?menuid=" + dto.MenuID));
                    if (dto.MenuID == currentMenu[0].MenuID)
                    {
                        if (base.SubSectorName.ToLower() == "emiten" || base.SubSectorName.ToLower() == "perusahaan publik")
                        {
                            if (dto.MenuName.ToLower() == "registrasi")
                                sbSitemap.AppendFormat("<li>{0}</li>", "Penawaran Umum");
                            else
                                sbSitemap.AppendFormat("<li>{0}</li>", dto.MenuName);
                        }
                        else
                            sbSitemap.AppendFormat("<li>{0}</li>", dto.MenuName);
                    }
                    else
                        sbSitemap.AppendFormat("<li><a href=\"{0}\" title=\"{1}\">{1}</a></li>", navigateUrl, dto.MenuName);
                }

            }

            ltrSiteMap.Text = sbSitemap.ToString();

        }

        private void AddItems(MenuItemCollection items, decimal? id, List<recMenu> menus)
        {
            var userTypes = ConfigurationManager.AppSettings["UserType"].Trim().Split(','); // Based On Web.Config
            var debiturUserID = int.Parse(userTypes[1].Trim().Split(':')[0]); // Get UserTypeID of Internal User
            var getParents = menus.Where(x => x.ParentMenuID == id).OrderBy(x => x.OrderSeq);

            foreach (recMenu menu in getParents)
            {
                MenuItem item = new MenuItem()
                {
                    Text = menu.MenuName,
                    NavigateUrl = (string.IsNullOrEmpty(menu.URL) ? "#" : menu.URL + (menu.URL.Contains('?') ? "&menuid=" + menu.MenuID : "?menuid=" + menu.MenuID))
                };
                if (base.SubSectorName.ToLower() == "emiten" || base.SubSectorName.ToLower() == "perusahaan publik")
                {
                    if (menu.MenuName.ToLower() == "registrasi")
                        item.Text = "Penawaran Umum";
                }

                this.AddItems(item.ChildItems, menu.MenuID, menus);
                items.Add(item);
                #region remarks for IsIndividual=true
                /*if (base.UserTypeID.Value.Equals(debiturUserID))
                {
                    if (base.IsIndividual)
                    {
                        if (menu.MenuName.ToLower() != "dasar pengenaan")
                        {
                            this.AddItems(item.ChildItems, menu.MenuID, menus);
                            items.Add(item);
                        }
                    }
                    else
                    {
                        this.AddItems(item.ChildItems, menu.MenuID, menus);
                        items.Add(item);
                    }
                }
                else
                {
                    this.AddItems(item.ChildItems, menu.MenuID, menus);
                    items.Add(item);
                }*/
                #endregion
            }
        }

    }
}